using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services;

/// <summary>
/// 标签服务实现
/// </summary>
public class TagService : ITagService
{
    private readonly PandaSystemContext _context;

    public TagService(PandaSystemContext context)
    {
        _context = context;
    }

    /// <inheritdoc />
    public async Task<IEnumerable<Tag>> GetAllAsync()
    {
        return await _context.Tags
            .Include(t => t.PostTags)
            .ToListAsync();
    }

    /// <inheritdoc />
    public async Task<Tag?> GetByIdAsync(Guid id)
    {
        return await _context.Tags
            .Include(t => t.PostTags)
            .FirstOrDefaultAsync(t => t.TagId == id);
    }

    /// <inheritdoc />
    public async Task<Tag?> GetByNameAsync(string name)
    {
        return await _context.Tags
            .Include(t => t.PostTags)
            .FirstOrDefaultAsync(t => t.Name == name);
    }

    /// <inheritdoc />
    public async Task<Tag> CreateAsync(Tag tag)
    {
        tag.TagId = Guid.NewGuid();
        _context.Tags.Add(tag);
        await _context.SaveChangesAsync();
        return tag;
    }

    /// <inheritdoc />
    public async Task<Tag> UpdateAsync(Tag tag)
    {
        _context.Entry(tag).State = EntityState.Modified;
        await _context.SaveChangesAsync();
        return tag;
    }

    /// <inheritdoc />
    public async Task DeleteAsync(Guid id)
    {
        var tag = await _context.Tags
            .Include(t => t.PostTags)
            .FirstOrDefaultAsync(t => t.TagId == id);
            
        if (tag != null)
        {
            // 删除标签关联的帖子标签
            _context.PostTags.RemoveRange(tag.PostTags);
            // 删除标签
            _context.Tags.Remove(tag);
            await _context.SaveChangesAsync();
        }
    }
} 